package com.jews.framework.json.jackson;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
import com.fasterxml.jackson.databind.deser.ValueInstantiator;
import com.fasterxml.jackson.databind.module.SimpleDeserializers;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.jews.framework.json.exclusion.JsonExcludableAnnotationExclusion;
import com.jews.framework.json.jackson.modifier.EasyjsonBeanDeserializerModifier;
import com.jews.framework.json.jackson.modifier.EasyjsonBeanSerializerModifier;
import com.jn.easyjson.core.JSON;
import com.jn.easyjson.core.annotation.DependOn;
import com.jn.easyjson.core.exclusion.ExclusionConfiguration;
import com.jn.easyjson.core.exclusion.IgnoreAnnotationExclusion;
import com.jn.easyjson.jackson.JacksonAdapter;
import com.jn.easyjson.jackson.JacksonConstants;
import com.jn.easyjson.jackson.Jacksons;
import com.jn.easyjson.jackson.deserializer.BooleanDeserializer;
import com.jn.easyjson.jackson.deserializer.Deserializers;
import com.jn.easyjson.jackson.deserializer.EnumDeserializer;
import com.jn.easyjson.jackson.ext.EasyJsonJacksonAnnotationIntrospector;
import com.jn.easyjson.jackson.ext.EasyJsonObjectMapper;
import com.jn.easyjson.jackson.serializer.BooleanSerializer;
import com.jn.easyjson.jackson.serializer.EnumSerializer;
import com.jn.langx.annotation.Name;
import lombok.SneakyThrows;
import sun.reflect.ReflectionFactory;

import java.io.IOException;
import java.lang.reflect.Constructor;

@Name("jackson")
@DependOn("com.fasterxml.jackson.databind.ObjectMapper")
public class CustomizeJacksonJSONBuilder extends com.jn.easyjson.jackson.JacksonJSONBuilder {
    private static final SimpleModule MODULE = new SimpleModule();
    private static volatile boolean moduleInited = false;

    static {
        makesureEasyJsonBaseModuleRegisted();
    }

    public CustomizeJacksonJSONBuilder() {
        super();
        dialectIdentify(Jacksons.JACKSON);
    }

    public CustomizeJacksonJSONBuilder(ExclusionConfiguration exclusionConfiguration) {
        super(exclusionConfiguration);
        dialectIdentify(Jacksons.JACKSON);
    }

    private static void makesureEasyJsonBaseModuleRegisted() {
        if (!moduleInited) {
            synchronized (CustomizeJacksonJSONBuilder.class) {
                if (!moduleInited) {
                    SimpleDeserializers simpleDeserializers = new Deserializers();
                    MODULE.setDeserializers(simpleDeserializers);

                    // boolean
                    MODULE.addSerializer(Boolean.class, new BooleanSerializer());
                    MODULE.addDeserializer(Boolean.class, new BooleanDeserializer());

                    // enum
                    MODULE.addDeserializer(Enum.class, new EnumDeserializer<>());
                    MODULE.addSerializer(Enum.class, new EnumSerializer<>());

                    MODULE.setSerializerModifier(new EasyjsonBeanSerializerModifier());
                    MODULE.setDeserializerModifier(new EasyjsonBeanDeserializerModifier());

                    moduleInited = true;
                }
            }
        }
    }

    private void configEnum(EasyJsonObjectMapper objectMapper) {
        // Enum: jackson default priority: ordinal() > toString() > name()
        // Our EnumSerializer priority: ordinal() > toString() > field > name()

        // step 1 : clear old config:
        SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
        serializationConfig = serializationConfig.withoutAttribute(JacksonConstants.SERIALIZE_ENUM_USING_FIELD_ATTR_KEY);

        DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig();
        deserializationConfig = deserializationConfig.withoutAttribute(JacksonConstants.SERIALIZE_ENUM_USING_INDEX_ATTR_KEY);
        deserializationConfig = deserializationConfig.withoutAttribute(JacksonConstants.SERIALIZE_ENUM_USING_FIELD_ATTR_KEY);

        // ordinal()
        if (serializeEnumUsingIndex()) {
            serializationConfig = serializationConfig.with(SerializationFeature.WRITE_ENUMS_USING_INDEX);
        }
        serializationConfig = serializationConfig.withAttribute(JacksonConstants.SERIALIZE_ENUM_USING_INDEX_ATTR_KEY, serializeEnumUsingIndex());
        deserializationConfig = deserializationConfig.withAttribute(JacksonConstants.SERIALIZE_ENUM_USING_INDEX_ATTR_KEY, serializeEnumUsingIndex());


        // toString()
        if (serializeEnumUsingToString()) {
            serializationConfig = serializationConfig.with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
            deserializationConfig = deserializationConfig.with(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
        }

        // field
        if (serializeEnumUsingField() != null) {
            serializationConfig = serializationConfig.withAttribute(JacksonConstants.SERIALIZE_ENUM_USING_FIELD_ATTR_KEY, serializeEnumUsingField());
            deserializationConfig = deserializationConfig.withAttribute(JacksonConstants.SERIALIZE_ENUM_USING_FIELD_ATTR_KEY, serializeEnumUsingField());
        }
        objectMapper.setDescrializationConfig(deserializationConfig);
        objectMapper.setSerializationConfig(serializationConfig);
    }

    private void configBoolean(EasyJsonObjectMapper objectMapper) {
        SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
        serializationConfig = serializationConfig.withAttribute(JacksonConstants.SERIALIZE_BOOLEAN_USING_1_0_ATTR_KEY, serializeBooleanUsing1_0());
        serializationConfig = serializationConfig.withAttribute(JacksonConstants.SERIALIZE_BOOLEAN_USING_ON_OFF_ATTR_KEY, serializeBooleanUsingOnOff());

        DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig();
        deserializationConfig = deserializationConfig.withAttribute(JacksonConstants.SERIALIZE_BOOLEAN_USING_1_0_ATTR_KEY, serializeBooleanUsing1_0());
        deserializationConfig = deserializationConfig.withAttribute(JacksonConstants.SERIALIZE_BOOLEAN_USING_ON_OFF_ATTR_KEY, serializeBooleanUsingOnOff());

        objectMapper.setSerializationConfig(serializationConfig);
        objectMapper.setDescrializationConfig(deserializationConfig);
    }

    private void configDate(EasyJsonObjectMapper objectMapper) {
        SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
        serializationConfig = serializationConfig.withAttribute(JacksonConstants.SERIALIZE_DATE_USING_DATE_FORMAT_ATTR_KEY, serializeUseDateFormat());
        serializationConfig = serializationConfig.withAttribute(JacksonConstants.SERIALIZE_DATE_USING_TO_STRING_ATTR_KEY, serializeDateUsingToString());
        serializationConfig = serializationConfig.withAttribute(JacksonConstants.SERIALIZE_LOCALE, serializeUsingLocale());
        serializationConfig = serializationConfig.withAttribute(JacksonConstants.SERIALIZE_TIMEZONE, serializeUsingTimeZone());

        DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig();
        deserializationConfig = deserializationConfig.withAttribute(JacksonConstants.SERIALIZE_DATE_USING_DATE_FORMAT_ATTR_KEY, serializeUseDateFormat());
        deserializationConfig = deserializationConfig.withAttribute(JacksonConstants.SERIALIZE_DATE_USING_TO_STRING_ATTR_KEY, serializeDateUsingToString());
        deserializationConfig = deserializationConfig.with(serializeUsingTimeZone());
        deserializationConfig = deserializationConfig.with(serializeUsingLocale());
        deserializationConfig = deserializationConfig.withAttribute(JacksonConstants.SERIALIZE_LOCALE, serializeUsingLocale());
        deserializationConfig = deserializationConfig.withAttribute(JacksonConstants.SERIALIZE_TIMEZONE, serializeUsingTimeZone());

        objectMapper.setSerializationConfig(serializationConfig);
        objectMapper.setDescrializationConfig(deserializationConfig);
    }

    private void configNumber(EasyJsonObjectMapper objectMapper) {
        SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
        serializationConfig = serializationConfig.withAttribute(JacksonConstants.SERIALIZE_LONG_USING_STRING_ATTR_KEY, serializeLongAsString());
        serializationConfig = serializationConfig.withAttribute(JacksonConstants.SERIALIZE_NUMBER_USING_STRING_ATTR_KEY, serializeNumberAsString());

        DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig();
        deserializationConfig = deserializationConfig.withAttribute(JacksonConstants.SERIALIZE_LONG_USING_STRING_ATTR_KEY, serializeLongAsString());
        deserializationConfig = deserializationConfig.withAttribute(JacksonConstants.SERIALIZE_NUMBER_USING_STRING_ATTR_KEY, serializeNumberAsString());

        objectMapper.setSerializationConfig(serializationConfig);
        objectMapper.setDescrializationConfig(deserializationConfig);
    }

    private void configNulls(EasyJsonObjectMapper objectMapper) {
        if (serializeNulls()) {
            objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
            objectMapper.setConfig(objectMapper.getSerializationConfig()
                    .withAppendedAnnotationIntrospector(new EasyJsonJacksonAnnotationIntrospector())
                    .withAttribute(JacksonConstants.SERIALIZE_NULLS_ATTR_KEY, true)
            );
        } else {
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        }

    }

    @Override
    public JSON build() {
        makesureEasyJsonBaseModuleRegisted();
        EasyJsonObjectMapper mapper = new EasyJsonObjectMapper();
        mapper.setJsonBuilder(this);
        mapper.registerModule(MODULE);

        // 配置全局属性
        mapper.setSerializationConfig(mapper.getSerializationConfig().withAttribute(JacksonConstants.ENABLE_CUSTOM_CONFIGURATION, this.isEnableCustomConfiguration()));
        mapper.setDescrializationConfig(mapper.getDeserializationConfig().withAttribute(JacksonConstants.ENABLE_CUSTOM_CONFIGURATION, this.isEnableCustomConfiguration()));
        configNulls(mapper);
        configBoolean(mapper);
        configNumber(mapper);
        configEnum(mapper);
        configDate(mapper);
        if (!serializeNonFieldGetter()) {
            mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
        }
        mapper.configure(SerializationFeature.INDENT_OUTPUT, prettyFormat());
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 解决找不到无参构造器的情况
        mapper.addHandler(new DeserializationProblemHandler() {

            @Override
            public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser jsonParser, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException {
                return super.handleUnknownProperty(ctxt, jsonParser, deserializer, beanOrClass, propertyName);
            }

            @SneakyThrows
            @Override
            public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, ValueInstantiator valueInsta, JsonParser jsonParser, String msg) {
                Constructor<?> constructor = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(instClass);
                constructor.setAccessible(true);
                Object instance = constructor.newInstance();
                JsonDeserializer<Object> deserializer = ctxt.findRootValueDeserializer(ctxt.constructType(instClass));
                return deserializer.deserialize(jsonParser, ctxt, instance);
            }
        });

        ExclusionConfiguration exclusionConfiguration = this.getExclusionConfiguration();

        // 开启对 @Ignore 的支持
        IgnoreAnnotationExclusion ignoreAnnotationExclusion = new IgnoreAnnotationExclusion();
        exclusionConfiguration.appendExclusion(ignoreAnnotationExclusion, true, true);

        // 开启对 @JsonExcludable 注解的兼容
        JsonExcludableAnnotationExclusion jsonExcludableAnnotationExclusion = new JsonExcludableAnnotationExclusion();
        exclusionConfiguration.appendExclusion(jsonExcludableAnnotationExclusion, true, true);

        JacksonAdapter jsonHandler = new JacksonAdapter();
        jsonHandler.setObjectMapper(mapper);
        JSON json = new JSON();
        json.setJsonHandler(jsonHandler);
        return json;
    }

    @Override
    @SuppressWarnings("MethodDoesntCallSuperMethod")
    protected Object clone() throws CloneNotSupportedException {
        CustomizeJacksonJSONBuilder result = new CustomizeJacksonJSONBuilder(this.getExclusionConfiguration());
        this.copyTo(result);
        return result;
    }
}
